import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { config} from '../../shared/smartadmin.config';
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
declare var $: any;
@Component({
  selector: 'sa-stopCars',
  templateUrl: './stopCars.component.html',
})
export class StopCarsComponent implements OnInit {
	tableData = []; //table数据
	totalCount:number = 0; //分页总条数
	curPage :number= 1; //分页当前页
	pageSize :number= 10; //内置的分页每页条数
	deviceId :string= '';//设备ID
	selectedCarNumber:string='';
	selectedCompanyId :string= '';
	selectedCompanyName:string = '';
	companyId :string= '';
	startTime:string = '';//开始时间
	endTime:string = '';//结束时间
	minStopTime:string ='60';
	constructor(private jsonApiService: JsonApiService,private activatedRoute: ActivatedRoute,private router: Router) {
		activatedRoute.queryParams.subscribe(queryParams => {
			var s_nowPage=localStorage.getItem('s_nowPage');
			if(s_nowPage){
				this.curPage=Number(s_nowPage);
				this.startTime=localStorage.getItem('s_tableStratTime');
				this.endTime=localStorage.getItem('s_tableEndTime');
				$("#datetimepicker1").val(this.startTime);
				$("#datetimepicker2").val(this.endTime);
				localStorage.removeItem('s_nowPage')
				localStorage.removeItem('s_tableStratTime')
				localStorage.removeItem('s_tableEndTime')
			}
		});
	}
	//刷新
	refresh(){
		this.load();
	}
	ngOnInit() {
		var detailCar=localStorage.getItem('detailCar');
		if(detailCar){
			this.selectedCarNumber=detailCar;
			localStorage.removeItem('detailCar');
		}
		this.initDate().then(()=>this.load());//初始化日期,加载table表格数据
		System.import('script-loader!select2/dist/js/select2.min.js').then(()=>{
			System.import('assets/js/select2-zh-CN.js').then(()=>{
				this.selectCompany();//初始化select 2 车辆
			})
			System.import('assets/js/jstree/jstree.min.js').then(()=>{
				this.initCompanyList();//初始化公司树
				var tree_box = document.getElementById('tree_box');
				var company = document.getElementById('company');
				//公司树弹窗显示隐藏交互事件
				document.onclick=function(e:any){
					if(!(e.target === company||e.target.className === 'jstree-children'||e.target.className === 's_del_icon'||e.target.className === 'jstree-node  jstree-leaf'||e.target.className === 'jstree-icon jstree-ocl'||e.target.className ==='vision_tree'||e.target.className === 'jstree-node jstree-leaf jstree-closed')){ 
				        tree_box.className = tree_box.className.replace("tree_open","");
				   	} 
				}
			})
		})
	}
	ngOnDestroy(){
		document.onclick = null;
	}
	//初始化日期
	initDate(){
		var that = this;
		return new Promise(function (resolve, reject) {
			System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(()=>{
					System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(()=>{
						$("#datetimepicker1").datetimepicker({//时间插件
							format: "yyyy-mm-dd hh:ii:ss",
						    language: "zh-CN",
						    autoclose: true,
//						    minView : 2
						}).on("changeDate", function(e){
							var date = e.date;
							if(!date){return;}
							var time = common.getTimeMmss(date);
							$("#datetimepicker2").datetimepicker("setStartDate", time);
						});
						$("#datetimepicker2").datetimepicker({//时间插件
							format: "yyyy-mm-dd hh:ii:ss",
						    language: "zh-CN",
						    autoclose: true,
//						    minView : 2
						}).on("changeDate", function(e){
							var date = e.date;
							if(!date){return;}
							var time = common.getTimeMmss(date);
							$("#datetimepicker1").datetimepicker("setEndDate", time);
						});
//						if(that.startTime==''&&that.endTime==''){
//							var date = new Date();
//							$("#datetimepicker2").val(common.getTimeMmss(date));//当前时间
//							date.setDate(date.getDate() - 7);//设置前一周
//							$("#datetimepicker1").val(common.getTimeMmss(date));
//						}
						resolve();
					});
				}
			);
		})

	}
	//擦除公司所选值
	delText(){
		this.selectedCompanyName = '';
		this.selectedCompanyId = '';
		this.selectedCarNumber='';
		this.deviceId='';
		this.clearSelect2($("#carNumberSelect2"));//清除Select中的数据
		this.selectCompany();
		$('#company').val("");
		this.companySearch();
		if($('#tree_box')[0].className.indexOf('tree_open')>0){
			$('#company').focus();
		}
	}
	//打开公司树
	companyClick(){
		$('#tree_box').toggleClass('tree_open');
	}
	//公司树模糊搜索
	companySearch(){
		var value = $('#company').val();
		$("#tree").jstree(true).search(value);
		let searchResult = $('.jstree-search').length;
		if(searchResult < 1){
			return;
		}
		$('.jstree-search').each(function(index, obj) {
			if(index < 1) {//js树搜索定位到结果的第一个地方；
				var container = $('#vision_tree'),
				scrollTo = $(this);
				container.scrollTop(scrollTo.offset().top - container.offset().top + container.scrollTop() - 130);
				container.animate({scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop() - $('#vision_tree').height() * 0.3});
			}
		})
	}
	//初始化公司树数据
	initCompanyList(){
		var that = this;
	 	$('#tree').jstree({
			"core": {
				'data': function(obj, callback) {       
					var jsonstr = "[]";       
					var jsonarray = eval('(' + jsonstr + ')');
					var url = 'company/companytree.html';
					$.ajax({        
						type: "POST",
				        url: config.BaseURL + url,
				        dataType: "json",
						xhrFields: {
							withCredentials: true
						},
//				        async: false,
				        success: function(result) {
							jsonarray = result;
							callback.call(this, jsonarray);
						}         
					});            
			},
			"themes": {
				"responsive": true
			},
			"multiple": false,
			"animation": 200,
			"dblclick_toggle": true,
			"expand_selected_onload": true
		},
		"plugins": ["search"]
		}).bind("activate_node.jstree", function(e, obj) {
			var currentNode = obj.node; // 获取当前节点   
			that.selectedCompanyName = currentNode.text;
			that.selectedCompanyId = currentNode.id;
			that.queryCarListByCompanyId(currentNode.id);
			that.deviceId='';
			$('#company').val(currentNode.text).change();
			that.companySearch();
		})
	}
	//擦除车牌号码所选值
	del_carNumber(){
		this.deviceId = '';
		this.selectedCarNumber='';
		if(this.selectedCompanyId){
			this.queryCarListByCompanyId(this.selectedCompanyId)
		}else{
			//采用简单粗暴的方法清除;官方推荐的方法失效
			var str=$("<span class='select2-selection__placeholder'>请选择</span>");
			$('#carNumberSelect2').val("");
			$("#select2-carNumberSelect2-container").empty();
			$("#select2-carNumberSelect2-container").attr("title","");
			$("#select2-carNumberSelect2-container").prepend(str);
		}	
	}
	//初始化select2 车辆选项
	selectCompany(){
			var that = this;
	        $("#carNumberSelect2").select2({
		    	language : "zh-CN",
		    	placeholder :"请选择",
		    	minimumInputLength : 2,      //最少2个字符，select2才显示查询的内容
		    	ajax: {
		    		url: config.BaseURL+"stats/carListByCarNumber.html",
		    		dataType: 'json',
		    		delay: 50,
		    		method: "POST",
		    		xhrFields: {
			           withCredentials: true
			      	},
		    		data: function (params) {
		    		    return {
		    		   	 "carNumber" :  params.term // search term
		    		    };
		    		},
		    		processResults: function(data, params) {
						var options = new Array();
						// 小于10个数量才判断重复
						if(data.data.length<=10){
							let arr = []
							let sameCar = []
							// 判断相同的车牌号
							for (let index = 0; index < data.data.length; index++) {
								let car = data.data[index];
								if(arr.indexOf(car.carNumber)!=-1){
									sameCar.push(car.carNumber)
								}else{
									arr.push(car.carNumber);
								}
							}
							$(data.data).each(function(index, car) {
								if(sameCar.indexOf(car.carNumber)!=-1){
									options.push({
										id: car.deviceId,
										text: car.carNumber+"["+car.parentName+"]"
									})
								}else{
									options.push({
										id: car.deviceId,
										text: car.carNumber
									})
								}
							});
						}else{
							$(data.data).each(function(index, car) {
								options.push({
									id: car.deviceId,
									text: car.carNumber
								})
							});
						}
						return {
							results: options //获取查询后的结果
						};
					},
		    		cache: true
		         },
		         templateResult: this.formatRepo
		    }).on ("select2:select", function (e) {
				  	var data = e.params.data;
				  	that.deviceId = data.id;
					if(data.text.indexOf('[') > 0){
						that.selectedCarNumber = data.text.split('[')[0];
					} else {
						that.selectedCarNumber = data.text;
					}
	       });
	}
	//select2 格式回调函数
	formatRepo (state) {
		if (!state.id) {
			return state.text;
		}
		var $state = $('<span><i class="fa fa-car green"></i>&nbsp;&nbsp;' + state.text + '</span>');
		return $state;
	}
	//清除select2 数据
	clearSelect2(obj) {
		obj.empty();
		obj.prepend("<option value=''>请选择</option>");
	}
	//公司id拉取车辆
	queryCarListByCompanyId(companyId){
		let reqdata = 'companyId='+companyId;
		this.jsonApiService.http("stats/carlist.html", reqdata).subscribe(data => {
			var carlist = data.data;
        	var selectdata = [];
        	for(var i = 0 ; i < carlist.length ; i++) {
        		var obj = {
        			id:carlist[i].deviceId,
        			text:carlist[i].carNumber,
        		}
        		selectdata[i] = obj;
        	}
        	var selectObj = $("#carNumberSelect2");
        	this.clearSelect2(selectObj);//清除Select中的数据
        	selectObj.select2({
        		language : "zh-CN",
            	data : selectdata,//为Select添加数据
                templateResult : this.formatRepo
           });
		})
	}
	//查询
	search_data(){
		this.curPage = 1;
		this.load();
	}
	//加载list数据
	
	load() {
		this.startTime =  $('#datetimepicker1').val();
		this.endTime =  $('#datetimepicker2').val();
		let timeCheck=common.correctTimeParams(this.startTime,this.endTime,0);
		if(!timeCheck.status){
			this.jsonApiService.message(timeCheck.message);
			return;
		}
		let param = {
			"pageSize": this.pageSize,
			"nowPage": this.curPage,
			"parameters": {
				deviceId:this.deviceId,
				startTime:this.startTime,
				endTime:this.endTime,
				minParkingDuration:this.minStopTime
			}
		};
		let reqdata = 'gridPager=' + JSON.stringify(param);
		this.jsonApiService.http("parkPosition/getParkPositionList", reqdata).subscribe(data => {
			if(!data.exhibitDatas){
				this.tableData = [];
				this.totalCount = 0;
				return;
			}
			for(let item of data.exhibitDatas){
			
				item.totalTime=	common.secondToDate(item.totalTime);
			}
			this.tableData = data.exhibitDatas;
			this.totalCount = data.recordCount;
		})
	}
	del_date(){
		this.startTime = '';
		this.endTime ='';
		$("#datetimepicker1").val('').change();
		$("#datetimepicker2").val('').change();
		$("#datetimepicker2").datetimepicker("setStartDate", null);
		$("#datetimepicker1").datetimepicker("setEndDate", null);
	}
	//添加事件
	add_row(){
		this.router.navigate(['/data-statistics/stopCars/stopCars-page'],{
			queryParams: {
				id: '',
				type: 'new',
				nowPage:'',
			}
		});
	}
	//表格编辑
	updataEvent(row){
	var itemStr=JSON.stringify(row);
		this.router.navigate(['/data-statistics/stopCars/stopCars-page'], {
			queryParams: {
				id: row.id,
				type: 'updata',
				nowPage:this.curPage,
				itemData:itemStr,
				tableStratTime:this.startTime,
				tableEndTime:this.endTime,
				
			}
		});
	}
	//表格删除
	delEvent(row){
		this.jsonApiService.confirm_message("此操作将永久删除数据,确认要删除?").then(()=>{
			let reqdata = 'id=' + row.id;
			if(!row.id){
				this.jsonApiService.message('id不存在');
				return;
			}
			this.jsonApiService.http("parkPosition/deleteParkPosition", reqdata).subscribe(data => {
				this.jsonApiService.message(data.message);
				if(data.success){
					this.load();
				}
			})
		})
	}
	//分页回调
	paginate(e){
		this.curPage = e.page+1;
		this.pageSize = e.rows;
		this.load();
	}
	jumpRailManage(row){
		localStorage.setItem('storageRailName',row.name);
		this.router.navigate(['/data-statistics/rail/rail-manage'])
	}
}